package net.vkits.anjiamiao.application;

import net.vkits.anjiamiao.domain.model.Order;
import net.vkits.anjiamiao.domain.model.OriginalOrder;
import net.vkits.anjiamiao.domain.model.TradeStatus;
import net.vkits.anjiamiao.domain.repository.OrderRepository;
import net.vkits.anjiamiao.domain.service.OrderService;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ethan-liu on 2016/11/12.
 */
@Service
public class OrderApplicationService {
    private static final Logger logger = LoggerFactory.getLogger(OrderApplicationService.class);

    @Resource
    private DozerBeanMapper mapper;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderService orderService;

    @Transactional
    public Order addOrder(OriginalOrder originalOrder, String cellPhoneNum){
        return orderService.createOrder(originalOrder, cellPhoneNum);
    }

    @Transactional
    public void changeStatus(String id, String status) {
        orderService.changeStatus(id, status);
    }

    public Order getOrder(String id) {
        return orderRepository.findOne(id);
    }

    public Page<Order> getOrders(Pageable pageable) {
        return orderRepository.findAll(pageable);
    }

    public List<net.vkits.common.dto.Order> getOrderList(String cellPhoneNum) {
        List<net.vkits.common.dto.Order> orderList = new ArrayList<>();
        List<Order> orders = orderRepository.findByCellPhoneNumAndStatusAndDeletedFalse(cellPhoneNum, TradeStatus.TransferSuccess);
        orders.forEach(order -> {
            net.vkits.common.dto.Order orderDto = mapper.map(order.getOriginalOrder(), net.vkits.common.dto.Order.class);
            orderDto.setId(order.getId());
            orderDto.setLandlord(order.getLandlord());
            orderDto.setCreateTime(order.getCreateTime().toString());
            orderList.add(orderDto);
        });
        return orderList;
    }
}
